import javax.swing.JFrame;

import util.Config;
import util.Debug;
import dao.DBException;
import db.DBCheck;
/**
 * Start class for database check.
 * @author Jolle
 * @version 1.0.0
 */
public class StartDB {
	/**
	 * @param args could be "config" to force showing configuration dialog
	 * or any other string to suppress it.
	 * Without any args displaying the dialog is related to the flag in Config.
	 */
	public static void main(String[] args) {
		/* show debug window if debug flag set */
//		if (Config.DEBUG) {
//			Debug.show();
//		}
		/* check for configuration argument */
		if (args.length == 1) {
			Config.SHOW_DB_CONFIG_DIALOG = (args[0].equalsIgnoreCase("config"));
		}
		Debug.print("SHOW_DB_CONFIG_DIALOG: " + Config.SHOW_DB_CONFIG_DIALOG);
		/* run database check */
		DBCheck checkDB = new DBCheck();
		try {
			if (checkDB.initDB()) {
				Debug.print("\n*** DATABASE CHECK  P A S S E D  ***");
			}
			else {
				Debug.print("\n--- DATABASE CHECK CANCELLED ---");
			}
		} catch (DBException dbe) {
			writeException(dbe.getException());
			writeException(dbe);
		} catch (Exception e) {
			writeException(e);
		} finally {
			if (Debug.frame != null) {
				if (Debug.frame.isVisible()) {
					Debug.print("change DefaultCloseOperation for debug window");
					Debug.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				}
				else {
					Debug.print("close debug window");
					Debug.frame.dispose();
				}
			}
		}
	}
	
	private static void writeException(Exception e) {
		Debug.print("########## EXCEPTION INFO ##########");
		Debug.print("getMessage: " + e.getMessage());
		Debug.print("  getCause: " + e.getCause());
		Debug.print("  toString: " + e.toString());
		
		Debug.print("StackTrace: " + e.getStackTrace().toString());
		for (StackTraceElement ste : e.getStackTrace()) {
			Debug.print("     Class: " + ste.getClassName());
			Debug.print("      File: " + ste.getFileName());
			Debug.print("    Method: " + ste.getMethodName());
			Debug.print("      Line: " + ste.getLineNumber());
		}
		Debug.print("------------------------------------");
	}
}
